﻿/*******************************************************************************
 * Copyright © 2016 DJY 版权所有
 * Author: DJY
 * Description: 后台管理系统
 * Website：http://www.djyweb.cn
*********************************************************************************/
using System;
using System.Collections;
using System.Web;

using SysCache = System.Web.Caching.Cache;

namespace DJY.Code
{
    public class Cache : ICache
    {
        private static SysCache cache = HttpRuntime.Cache;

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        public T GetCache<T>(string cacheKey)
        {
            if (cache[cacheKey] != null)
            {
                return (T)cache[cacheKey];
            }
            return default(T);
        }

        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="cacheKey">缓存键</param>
        /// <param name="obj">缓存对象</param>
        public void SetCache(string cacheKey,object obj)
        {
            cache.Insert(cacheKey, obj, null, SysCache.NoAbsoluteExpiration, SysCache.NoSlidingExpiration);
        }

        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="cacheKey">缓存键</param>
        /// <param name="obj">缓存对象</param>
        /// <param name="expireTime">绝对过期时间</param>
        public void SetCache(string cacheKey, object obj, DateTime expireTime)
        {
            cache.Insert(cacheKey, obj, null, expireTime, SysCache.NoSlidingExpiration);
        }

        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="cacheKey">缓存键</param>
        /// <param name="obj">缓存对象</param>
        /// <param name="noSlidingExpiration">相对过期时间</param>
        public void SetCache(string cacheKey, object obj, TimeSpan noSlidingExpiration)
        {
            cache.Insert(cacheKey, obj, null, SysCache.NoAbsoluteExpiration, noSlidingExpiration);
        }

        /// <summary>
        /// 移除缓存
        /// </summary>
        /// <param name="cacheKey">缓存键</param>
        public void RemoveCache(string cacheKey)
        {
            cache.Remove(cacheKey);
        }

        /// <summary>
        /// 清空缓存
        /// </summary>
        public void RemoveCache()
        {
            IDictionaryEnumerator CacheEnum = cache.GetEnumerator();
            while (CacheEnum.MoveNext())
            {
                cache.Remove(CacheEnum.Key.ToString());
            }
        }
    }
}
